package com.flong.modules.utils;

import java.io.IOException;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

/**
 * @Description WebFilter过滤器 initParams 初始化参数配置 description给过滤器描述
 *              dispatcherTypes转发类型 此类处理方式同等web.xml配置过滤器
 * @ClassName CharacterEncodingFilter
 * @Date 2017年3月7日 上午8:46:29
 * @Author liangjilong
 * @Copyright (c) All Right Reserved Flong, 2017.
 */
@WebFilter
	(filterName="FilterConfig",urlPatterns="/*",//配置过滤器名称和拦截链接规则
	initParams = {
        @WebInitParam(name = "encoding", value = "utf-8")//初始化编码参数
    },
    description = "FilterConfig",//过滤器的描述
    dispatcherTypes = {DispatcherType.REQUEST, DispatcherType.FORWARD}//转发类型
)
public class CharacterEncodingFilter implements Filter {

	protected String encoding = null;//编码
	protected FilterConfig filterConfig = null;//过滤器配置
	protected boolean ignore = true;//忽略
	
	/**
	 * 销毁
	 */
	@Override
	public void destroy() {
		this.encoding = null;
		this.filterConfig = null;
	}
	/**
	 * 过滤请求和响应的编码
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if (ignore || (request.getCharacterEncoding() == null)) {
			String encoding = setCharacterEncoding(request);
			if (encoding != null)
				request.setCharacterEncoding(encoding);
		}
		chain.doFilter(request, response);
	}
	/**
	 * 初始化过滤器配置
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		this.encoding = filterConfig.getInitParameter("encoding");
		String value = filterConfig.getInitParameter("ignore");
		if (value == null)
			this.ignore = true;
		else if (value.equalsIgnoreCase("true"))
			this.ignore = true;
		else if (value.equalsIgnoreCase("yes"))
			this.ignore = true;
		else
			this.ignore = false;
	}
	
	/**
	 * @Description 设置编码
	 * @Author		liangjilong
	 * @Date		2017年3月7日 上午8:43:55
	 * @param request
	 * @return 		参数
	 * @return 		String 返回类型
	 */
	protected String setCharacterEncoding(ServletRequest request) {
		return (this.encoding);
	}
}
